import {$APIMAP, $APIDATA} from '@/api/api.js'
import {isH5} from '@/utils/Platform.js'
import qs from 'qs';
const commonMenuClolrs = ['#3192f7', '#f5764d', '#59c27f', '#f56862', '#f79923'];
const LocalTestServer = 'http://localhost:8080';
const JSON5 = require('json5');
import {mapState, mapMutations} from 'vuex';	
export default {
    couputed: {
        ...mapState['userInfo', 'menuConfigs', 'glbalConfig']
    },
    methods: {
        ...mapMutations(['setMenuConfigs']),
        waitVariable: function (name) {
            var vm = this;
            if (!global.waitObj[name]) {
                global.waitObj[name] = 1;
            } else {
                global.waitObj[name]++;
            }
            return new Promise((resolve, reject) => {
                var v = vm[name];
                if (!v) {
                    if (global.waitObj[name] > 100) {
                        reject();
                        return;
                    }
                    console.log('等待变量', name);
                    setTimeout(() => {
                        v = vm.waitVariable(name);
                        resolve(v);
                    }, 200)
                } else {
                    global.waitObj[name] = 0;
                    resolve(v)
                }
            });
        },
        _getSpaceConfig: function () {
            var vm = this;
            return new Promise(resolve => {
                var spaceConfig = uni.getStorageSync('spaceConfig');
                if (spaceConfig) {
                    vm.setMenuConfigs({
                        commonMenus: vm.$Util.cloneObject(spaceConfig.commonMenus),
                        extMenus: vm.$Util.cloneObject(spaceConfig.extMenus),
                        menuButtons: vm.$Util.cloneObject(spaceConfig.menuButtons),
                        topMenus: vm.$Util.cloneObject(spaceConfig.topMenus),
                    })
                    resolve(spaceConfig);
                } else {
                    vm.getAndLoad('获取空间配置', '?spaceName=05info', (res) => {
                        // 设置按钮
                        var commonMenus = res.data.commonMenus;
                        vm.$Util.mergeVariables(commonMenus, commonMenuClolrs, 'color');
                        commonMenus.forEach(n => {
                            n.style = `background: linear-gradient(0, ${n.color}, ${n.color}90)`;
                        });
                        vm.setMenuConfigs({
                            commonMenus: vm.$Util.cloneObject(commonMenus),
                            extMenus: vm.$Util.cloneObject(res.data.extMenus),
                            menuButtons: vm.$Util.cloneObject(res.data.menuButtons),
                            topMenus: vm.$Util.cloneObject(res.data.topMenus),
                        })
                        uni.setStorageSync('spaceConfig', res.data);
                        resolve(res.data);
                    });
                }
            });

        },
        getSpaceConfig: function () {
            var vm = this;
            return new Promise(resolve => {
                if (vm.menuConfigs) {
                    resolve(vm.menuConfigs);
                } else {
                    var userId = vm.userInfo ? vm.userInfo.userId : '';
                    vm.getAndLoad('获取模块配置', '/mobile/wx/newApi/getModules.jsp?userId=' + userId + '&openId=' + uni.getStorageSync('openId'), (res) => {
                        // 设置按钮
                        var commonMenus = res.data.commonMenus;
                        vm.$Util.mergeVariables(commonMenus, commonMenuClolrs, 'color');
                        commonMenus.forEach(n => {
                            n.style = `background: linear-gradient(0, ${n.color}, ${n.color}90)`;
                        });
                        vm.setMenuConfigs({
                            spaceName: res.spaceName,
                            topAd: vm.$Util.cloneObject(res.data.topAd),
                            commonMenus: vm.$Util.cloneObject(commonMenus),
                            extMenus: vm.$Util.cloneObject(res.data.extMenus),
                            menuButtons: vm.$Util.cloneObject(res.data.menuButtons),
                            contents: vm.$Util.cloneObject(res.data.contents),
                            topMenus: vm.$Util.cloneObject(res.data.topMenus),
                        })
                        uni.setStorageSync('spaceConfig', res.data);
                        resolve(res.data);
                    });
                }
            });

        },
        throttle: function (duration = 1000) {
            if (this.__buttonLocked) {
                uni.$u.toast('请的操作太快, 请稍后再试');
                throw(new Error('等一等'))
            } else {
                this.__buttonLocked = true;
                setTimeout(() => {
                    this.__buttonLocked = false;
                }, duration);
            }
        },
        testPing: function (url) {
            // #ifdef MP-WEIXIN
            url = LocalTestServer + url;
            // #endif
            return new Promise((resolve, reject) => {
                var flag = false;
                setTimeout(() => {
                    if (!flag) {
                        global.localJSONConfigStarted = 'false';
                        console.log('测试环境JSON服务配置链接超时');
                        resolve({statusCode: 400});
                    }
                }, 1000);
                uni.request({
                    url: url,
                    success: (res) => {
                        flag = true;
                        resolve(res);
                    },
                    fail: (err) => {
                        resolve({statusCode: 400});
                        // reject(err);
                    }
                });
            });
        },
        getFmtImage: function (v) {
            if (v && v.startsWith('/') && !v.startsWith('/static')) {
                return this.API_PREFIX + v;
            } else {
                return v;
            }
        },
        getAndLoadV2: async function (name, url, args) {
            var config = await this.waitVariable('globalConfig');
            var urlPrefix = (config.APIMAP || {})[name] || '';
            return this.getAndLoad(name, urlPrefix + url, args);
        },
        getAndLoad: async function (name, url, arg3) {
            if ($APIMAP[name]) {
                url = $APIMAP[name] + url;
            }
            var requestMethod = url.startsWith('::POST') ? 'POST' : 'GET';
            var data = {};
            if (requestMethod === 'POST') {
                url = url.replace('::POST', '');
                data = qs.parse(url.slice(url.indexOf('?') + 1));
            }
            var requestUrl = url;
            
            if (!(url.startsWith('/static') || url.startsWith('./') || url.startsWith('http')) || !isH5) {
                requestUrl = this.API_PREFIX + url;
            }
            if (global.ipId) {
                var fh = requestUrl.includes('?') ? '&' : '?';
                fh = requestUrl.endsWith(fh) ? '' : fh;
                requestUrl += fh + 'ipId=' + global.ipId;
            }

            var openId = uni.getStorageSync('openId');
            if (openId && !requestUrl.includes('openId=')) {
                var fh = requestUrl.includes('?') ? '&' : '?';
                fh = requestUrl.endsWith(fh) ? '' : fh;
                requestUrl += fh + 'openId=' + openId;
            }

            var isDevelopment = false;
            // #ifdef MP-WEIXIN
            isDevelopment = __wxConfig.envVersion == 'develop';
            // #endif
            // #ifdef H5
            isDevelopment = location.hostname == 'localhost';
            // #endif

            if (!global.localJSONConfigStarted && isDevelopment) {
                var result = await this.testPing('/wxAssets/wxJSON/globalConfig.json');            
                if (!result || (result && result.statusCode != 200)) {
                    global.localJSONConfigStarted = 'false';
                    console.log('测试环境JSON服务配置未启动， 配置文件服务自动跳转到正式环境');
                } else {
                    global.localJSONConfigStarted = 'true';
                    console.log('测试环境JSON服务配置是启动的， 配置文件会读本地的配置');
                }
            }
            
            if (global.localJSONConfigStarted == 'true' && isDevelopment && url.includes('wxJSON')) {
                // #ifndef MP-WEIXIN
                requestUrl = './static/configs' + url.split('wxJSON')[1];
                // #endif

                // #ifdef MP-WEIXIN
                requestUrl = LocalTestServer + '/wxAssets/wxJSON' + requestUrl.split('/wxJSON')[1];
                // #endif
            }

            var keys = Object.keys($APIDATA);
            var fakeKey = keys.find(key => requestUrl.includes(key));
            
            if (fakeKey) {
                setTimeout(() => {
                    if (typeof arg3 == 'function') {
                        arg3(JSON.parse(JSON.stringify($APIDATA[fakeKey])));
                    } else {
                        (arg3.success || args.complete)(JSON.parse(JSON.stringify($APIDATA[fakeKey])));
                    }
                }, 200);
                return;
            }
            if (typeof arg3 == 'function') {
                uni.request({
                    url: requestUrl,
                    header: {
                        'Cookie': uni.getStorageSync('loginCookie'),
                        token: this.token
                    },
                    complete: (res => {
                        if(res.cookies && res.cookies.length){
                            uni.setStorageSync('loginCookie', res.cookies[0]);
                        }
                        if (typeof res.data == 'string') {
                            try {
                                arg3(JSON5.parse(res.data));
                            } catch (e) {
                                arg3(res.data);
                            }
                        } else {
                            arg3(res.data);
                        }
                    })
                });
            } else {
                uni.request({
                    url: requestUrl,
                    method: requestMethod,
                    data,
                    header: {
                        token: this.token
                    },
                    ...arg3
                });
            }
        },
        uploadFile: function (url, arg3) {
            uni.uploadFile({
                url: this.API_PREFIX + '/api/miniapp/v1/uploadImg.jsp', // 仅为示例，非真实的接口地址
                filePath: url,
                name: 'file',
                formData: {
                    user: 'test'
                },
                complete: (res) => {
                    arg3(JSON.parse(res.data))
                }
            });
        },
        doWxLogin: function (force) {
            var vm = this;
            var openId = uni.getStorageSync('openId');
            if (openId && openId.length > 15 && !force) {
                return new Promise(resolve => {
                    resolve({openId: openId});
                });
            } else {
                // #ifdef MP-WEIXIN
                    return new Promise(resolve => {
                        uni.login({
                            provider: 'weixin',
                            success: function (res) {
                                vm.getAndLoad('获取openId', '/mobile/wx/newApi/wx/weChatCode.jsp?code=' + res.code, function (res) {
                                    if (res.success && res.openid) {
                                        uni.setStorageSync('openId', res.openid);
                                        if (!res.openId) {res.openId = res.openid;}
                                        resolve(res);
                                    } else {
                                        return vm.doWxLogin(force);
                                    }
                                });
                            }
                        });
                    });
                // #endif
                // #ifndef MP-WEIXIN
                return new Promise(resolve => {
                    uni.setStorageSync('openId', "o52VT5A7Ojgu3A6drKvXchyqtKQ0");
                    resolve({"session_key":"lCWgi20FoOwKoZoB70WVKA==","openid":"o52VT5A7Ojgu3A6drKvXchyqtKQ0","success":true,"msg":""});
                });
                // #endif
            }
            
        },
        gotoH5Page: function (url) {
            global.listPageNeedReload = true;
            uni.navigateTo({ url: '/pages/openh5/index?url=' + encodeURIComponent(url) });
        }
    }
}